import os
import sys
from common.logger import logger


def modules_import(project_name: str = None, verbose_lv: int = 1):
    """enable import functions from within projects

    Parameters
    ----------
    project_name : str
        project folder name under the satellite-platform/projects directory
        (e.g. "20210201_CroplandInstanceSegmentation_superpixel")
        , by default None
    verbose_lv : int, optional
        0: do not report to logger
        1: report message to logger
        , by default 1
    """
    if project_name is None:
        raise ValueError("modules_import: project_name unknown")
    # NOTE: import project codes
    cwd_parts = os.getcwd().split(os.path.sep)
    if project_name in cwd_parts:
        # idx_val = [i for i, part in enumerate(cwd_parts) if part == project_name][0] + 1
        idx_val = cwd_parts.index(project_name) + 1
        prj_path = os.path.sep.join(cwd_parts[:idx_val])
    else:
        idx_val = cwd_parts.index("satellite-platform") + 1
        prj_path = os.path.join(
            os.path.sep.join(cwd_parts[:idx_val]), "projects", project_name
        )
        if not os.path.isdir(prj_path):
            raise ValueError(
                f"modules_import failed --> prj_path not found: {prj_path}."
            )
    sys.path.append(prj_path)
    if verbose_lv > 0:
        logger.info(f"user may now import functions from <{prj_path}>.")
